package com.hkts.naturalgasauthentication.utils;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
public class UploadAndDownloadUtils {
  //上传到服务器文件夹中
  public final static String UPLOAD_PATH_PREFIX = "static/uploadFile/";
  public static String uploadUtils(MultipartFile uploadFile, HttpServletRequest request){
    if(uploadFile.isEmpty()){
      //返回选择文件提示
      return "请选择上传文件";
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    //构建文件上传所要保存的"文件夹路径"--这里是相对路径，保存到项目根路径的文件夹下
    String realPath = new String("xboot-fast/src/main/resources/" + UPLOAD_PATH_PREFIX);
    log.info("-----------上传文件保存的路径【"+ realPath +"】-----------");
    String format = sdf.format(new Date());
    //存放上传文件的文件夹
    File file = new File(realPath + format);
    log.info("-----------存放上传文件的文件夹【"+ file +"】-----------");
    log.info("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径【"+ file.getAbsolutePath() +"】-----------");
    if(!file.isDirectory()){
      //递归生成文件夹
      file.mkdirs();
    }
    //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
    String oldName = uploadFile.getOriginalFilename();
    log.info("-----------文件原始的名字【"+ oldName +"】-----------");
    String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());
    log.info("-----------文件要保存后的新名字【"+ newName +"】-----------");
    try {
      //构建真实的文件路径
      File newFile = new File(file.getAbsolutePath() + File.separator + oldName);
      //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
      uploadFile.transferTo(newFile);
      String filePath =  "/uploadFile/" + format + oldName;
      return filePath;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "上传失败!";
  }
//视频资源
public static void downLoadVido(HttpServletResponse response,String filePath){
  String[] uploadFiles = filePath.split("uploadFile");
  String property = System.getProperty("user.dir");
  filePath =property+"\\xboot-fast\\src\\main\\resources\\static\\uploadFile"+uploadFiles[1];
  try{
    FileInputStream ff=new FileInputStream(filePath);
    OutputStream out=null;
    int size=ff.available();
    byte[] data=new byte[size];
    ff.read(data);
    ff.close();
    ff=null;
    response.setContentType("video/mp4");
    out=response.getOutputStream();
    out.write(data);
    out.flush();
    out.close();
  }catch(Exception e){
    e.printStackTrace();
  }
}

  //下载
  public static void downLoad(HttpServletResponse response,String filePath)throws UnsupportedEncodingException{
    String[] uploadFiles = filePath.split("uploadFile");
    String property = System.getProperty("user.dir");
    filePath =property+"\\xboot-fast\\src\\main\\resources\\static\\uploadFile"+uploadFiles[1];

    File file = new File(filePath);
    String filename = file.getName();
    if(file.exists()){ //判断文件父目录是否存在
      response.setContentType("application/vnd.ms-excel;charset=UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "iso8859-1"));
      byte[] buffer = new byte[1024];
      FileInputStream fis = null; //文件输入流
      BufferedInputStream bis = null;
      OutputStream os = null; //输出流
      try {
        os = response.getOutputStream();
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        int i = bis.read(buffer);
        while(i != -1){
          os.write(buffer);
          i = bis.read(buffer);
        }

      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      System.out.println("----------file download---" + filename);
      try {
        bis.close();
        fis.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  //Ftp InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"));
 public  static  String  handleFtpStrToFile(String str)throws  Exception{

    InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"));
    String filePath = new  DateTime().toString("/yyyyMMdd/");
   String backUrl = FtpUtil.putImages(is, filePath, UUID.randomUUID().toString() + ".text");
   return backUrl;
  }
 //文件转字符串
  public  static  String  handleStrToFile(String str){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    String realPath = new String("xboot-fast/src/main/resources/" + UPLOAD_PATH_PREFIX);
    String format = sdf.format(new Date());
    File file = new File(realPath + format);
    if(!file.isDirectory()){
      //递归生成文件夹
      file.mkdirs();
    }
    String newName = UUID.randomUUID().toString() + ".text";
    File newFile = new File(file.getAbsolutePath() + File.separator + newName);
    String backFileName=realPath + format+newName;
    FileWriter fwriter = null;
    try {
      // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
      fwriter = new FileWriter(newFile.getPath(), true);
      fwriter.write(str);
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
        fwriter.flush();
        fwriter.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return backFileName;
  }
  //文件转字符串
  //文件转字符串
  public  static  String  handleFileToStr(String filePath) throws Exception{
    String property = System.getProperty("user.dir");
    filePath =property+"\\"+ filePath;
    StringBuffer buffer = new StringBuffer();
    BufferedReader bf= new BufferedReader(new FileReader(filePath));
    String s = null;
    while((s = bf.readLine())!=null){//使用readLine方法，一次读一行
      buffer.append(s.trim());
    }
    String str = buffer.toString();
    return str;
  }
  //删除文件
  public static void deleteFile(String filePath){
    String[] uploadFiles = filePath.split("uploadFile");
    String property = System.getProperty("user.dir");
    filePath =property+"\\xboot-fast\\src\\main\\resources\\static\\uploadFile"+uploadFiles[1];
    File file = new File(filePath);// 读取
    file.delete();
  }
  ///////////
 /* public static void fetchFrame(String videofile, HttpServletResponse response)

  }*/
  //文件下载
  public static void downloadFile(String filePath, HttpServletResponse response, HttpServletRequest request) {
    String[] uploadFiles = filePath.split("uploadFile");
    String property = System.getProperty("user.dir");
    filePath =property+"\\xboot-fast\\src\\main\\resources\\static\\uploadFile"+uploadFiles[1];

    File file = new File(filePath);

    //相应头的处理
    //清空response中的输出流
    response.reset();
    //设置文件大小
    response.setContentLength((int) file.length());
    //设置Content-Type头
    response.setContentType("application/octet-stream;charset=UTF-8");
    //设置Content-Disposition头 以附件形式解析
    String encodedFilename = getEncodedFilename(request, file.getName());
    response.addHeader("Content-Disposition", "attachment;filename=" + encodedFilename);

    //将来文件流写入response中
    FileInputStream fileInputStream = null;
    ServletOutputStream outputStream = null;
    try {
      //获取文件输入流
      fileInputStream = new FileInputStream(file);
      //创建数据缓冲区
      byte[] buffers = new byte[1024];
      //通过response中获取ServletOutputStream输出流
      outputStream = response.getOutputStream();
      int length;
      while ((length = fileInputStream.read(buffers)) > 0) {
        //写入到输出流中
        outputStream.write(buffers, 0, length);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //流的关闭
      if(fileInputStream != null){
        try {
          fileInputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (outputStream != null) {
        try {
          outputStream.flush();
          outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }


  /**
   * 获取URL编码后的原始文件名
   * @param request ：客户端请求
   * @param originalFileName ：原始文件名
   * @return ：
   */
  private static String getEncodedFilename(HttpServletRequest request, String originalFileName) {

    String encodedFilename = null;
    String agent = request.getHeader("User-Agent");
    if(agent.contains("MSIE")){
      //IE浏览器
      try {

        encodedFilename = URLEncoder.encode(originalFileName, "utf-8");
        encodedFilename = encodedFilename.replace("+", " ");
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }else if(agent.contains("Firefox")){
      //火狐浏览器
      BASE64Encoder base64Encoder = new BASE64Encoder();
      encodedFilename = "=?utf-8?B?" + base64Encoder.encode(originalFileName.getBytes(StandardCharsets.UTF_8))+"?=";
    }else{
      //其他浏览器
      try {
        encodedFilename = URLEncoder.encode(originalFileName, "utf-8");
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    return encodedFilename;
  }

  ///////////
  public static Object uploadPicture(MultipartFile uploadFile) {
    //1、给上传的图片生成新的文件名
    //1.1获取原始文件名
    String oldName = uploadFile.getOriginalFilename();
    //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
    String newName = IDUtils.genImageName();
    assert oldName != null;
    newName = newName + oldName.substring(oldName.lastIndexOf("."));
    //1.3生成文件在服务器端存储的子目录
    String filePath = new  DateTime().toString("/yyyyMMdd/");
    //2、把图片上传到图片服务器
    //2.1获取上传的io流
    InputStream input = null;
    try {
      input = uploadFile.getInputStream();
    } catch (IOException e) {
      e.printStackTrace();
    }
    //2.2调用FtpUtil工具类进行上传
    return FtpUtil.putImages(input, filePath, newName);
  }
   //下载ftp远程下载
   public static void  down(String remoteFileUrl, String saveFileName,  HttpServletResponse response)throws  Exception {
    FtpUtil.down(remoteFileUrl,saveFileName,response);
     // 返回保存后的文件路径
   }
   //下载文件转字符串
   public static String   ftpFileToString(String remoteFileUrl)throws  Exception {
     String str = FtpUtil.ftpFileToString(remoteFileUrl);
     return str;
   }
}
//视频第一怔缩略图
